@extends('mobile.template.layout')

@section('resources')
  <script type="text/javascript">
    <!-- rem单位基准声明 -->
    var designWidth = 375, maxWidth = 500, bodyFontSize = 14, baseFontSize = 37.5
    _setBaseFontSize()
    _setBodyFontSize()
    _setReCalcRem()

    // 设置文档默认字体
    function _setBodyFontSize () {
      if (document.body) document.body.style.fontSize = bodyFontSize + 'px'
      else document.addEventListener('DOMContentLoaded', _setBodyFontSize, false)
    }

    // 设置REM基准字号 1rem = 设计图尺寸 / 屏幕dpr / 基准字号
    function _setBaseFontSize () {
      var clientWidth = document.documentElement.clientWidth
      var rem = baseFontSize * (clientWidth > maxWidth ? maxWidth : clientWidth) / designWidth
      document.documentElement.style.fontSize = rem + 'px'
    }

    // 设置屏幕尺寸变化事件代理, 重新计算REM基准尺寸
    function _setReCalcRem () {
      document.addEventListener('DOMContentLoaded', _setBaseFontSize, false)
      window.addEventListener('orientationchange' in window ? 'orientationchange' : 'resize', _setBaseFontSize, false)
    }
  </script>
  <link href="{{env('CDN_RESOURCE')}}/mobile/campaign/award/css/award.css" rel="stylesheet" type="text/css">
@stop

@section('header')
  <div class="header">
    <img class="banner" src="{{env('CDN_RESOURCE')}}/mobile/campaign/award/img/banner.jpg" alt="">
    <div class="play-icon" id="viewVideo" style="top: 7.8rem;left: 4.4rem;"></div>
    <div class="switch-account">切换账户</div>
  </div>
@stop

@section('section')

  <div class="section" style="padding: 8px;">
    <div id="activity_timer">
      <span>剩余时间:</span>
      <span class="day1 activity-time js-activity-time js-activity-time-day">0</span><!--
   --><span class="day2 activity-time js-activity-time js-activity-time-day">3</span><!--
   --><span class="activity-unit">天</span><!--
   --><span class="hour1 activity-time js-activity-time js-activity-time-hour">0</span><!--
   --><span class="hour2 activity-time js-activity-time js-activity-time-hour">0</span><!--
   --><span class="activity-unit">:</span><!--
   --><span class="min1 activity-time js-activity-time js-activity-time-minute">0</span><!--
   --><span class="min2 activity-time js-activity-time js-activity-time-minute">0</span>
    </div>
  </div>

  <div class="section" style="padding:10px 0;">
    <div id="process" class="process"></div>
    <div id="groupBuyDetail" style="position: relative">
      <div id="groupBuyList" class="group-buy-list"></div>
      <div id="dividerList" class="g-m-divider"></div>
    </div>
    <a id="group-btn" class="group-btn">立即开团</a>
  </div>

  <div class="section" style="padding:10px 0;">
    <div class="header">
      活动进度
    </div>
    <div class="camp-step">
      <div class="item">
        <div id="step-create" class="group-buy-step1 icon"></div>
        <span>开团当团长</span>
      </div>
      <div class="item">
        <div id="step-join" class="group-buy-step2 icon"></div>
        <span>参团支付</span>
      </div>
      <div class="item">
        <div id="step-share" class="group-buy-step3 icon"></div>
        <span>邀请好友参团</span>
      </div>
      <div class="item">
        <div id="step-done" class="group-buy-step4 icon"></div>
        <span>团购完成</span>
      </div>
      <div>
        <div class="connect-line"></div>
        <div class="connect-line"></div>
        <div class="connect-line"></div>
      </div>
    </div>
  </div>

  <div class="section" style="padding:10px 0 40px 0;">
    <div class="group-title"><span>活动信息</span></div>
    <div id="group_rules">
      <p>
        1.开团、参团后80课时直接到账，团倒计时结束后，根据参团人数自动获得对应的赠课（即单人购买¥3200/80课时，2人团每人可得82课时，5人团每人85课时，10人团每人90课时，20人团每人95课时）赠课不关联学费金额。</p>
      <p>2.购买后即可约课，团购课时一年内有效；若到期未使用完，可申请延期。</p>
    </div>
  </div>

@stop

@section('script')
  <script type="text/javascript">
    // 参数说明
    // gid - 表示团id, 有带这个参数的时候将会获取这个团的信息
    // fc  - 表示强制开团, 有带这个参数时, 不会获取团信息, 直接就开团

    !function () {
      var user = null;
      var CDN_RESOURCE = "{{env('CDN_RESOURCE')}}"
      var pid = 19
      var gid = getGid() // 团id
      var forceCreate = !!+utils.getQueryString('fc') // 强制开团参数
      var buyers = []    // 团成员信息
      var buyersIds = [] // 团成员id信息
      var page = 1       // 团成员分页页码
      var pageSize = 10  // 团成员分页每页最大数量
      var status = 0     // 团购状态
      var starCount = null
      var campUrl = window.location.protocol + '//' + window.location.host + '/wx/award';

      var stepCreate = $('#step-create'),
          stepJoin = $('#step-join'),
          stepShare = $('#step-share'),
          stepDone = $('#step-done'),
          groupBtn = $('#group-btn'),
          day1  = $('#activity_timer .day1'),
          day2  = $('#activity_timer .day2'),
          hour1 = $('#activity_timer .hour1'),
          hour2 = $('#activity_timer .hour2'),
          min1  = $('#activity_timer .min1'),
          min2  = $('#activity_timer .min2');

      window.wxconfig = null
      initWxConfig()
      activeShare()
      var account = new Account();
      account.forceLogin = false;
      account.getUserInfo(function (err, userInfo) {
        account.forceLogin = true;
        user = userInfo;
        if (userInfo && userInfo.shareFlag) {
          activeShare(userInfo.shareFlag)
        }
        init()
      });

      function init () {
        // 是否强制开团
        if (!forceCreate && (gid || (!gid && !!user))) {
          getGroupBuyInfo()
        } else {
          // 强制开团或者没有gid并没登录的情况
          console.log('强制开团或者没有gid并没登录的情况');
          setGroupBuyStatus(0)
        }
      }

      // 获取团购信息
      function getGroupBuyInfo(success, fail) {
        account.ajax({
          auth: !!user,
          type: 'POST',
          path: '/s/products/' + pid + '/buying',
          data: gid ? {groupBuyingId: encodeURIComponent(gid)} : '',
          success: function (result) {
            gid = result.id
            activeShare(user ? user.shareFlag : '');
            buyersIds = result.buyers // 将团购成员id存入变量
            setGroupBuyCountDown(result.endAt * 1000)
            renderProcess()
            getGroupBuyerList()
            // 先判断团是否结束
            if (result.status) {
              // status = 1 表示团购已经结束, 不管在不在团里都显示重新开团
              console.log('status = 1 团购已经结束, 即使在团里也重新开团');
              setGroupBuyStatus(3)
            } else {
              // status = 0 表示团购还没结束, 这时候需要判断是否在团里
              if (!!user && inGroup()) {
                // 在团里了, 所以显示分享
                console.log('status = 0 团没结束并在团里了, 显示分享');
                setGroupBuyStatus(2)
              } else {
                // 不在团里, 也还没结束, 则可以参团
                console.log('status = 0 团购还没结束, 可以参团');
                setGroupBuyStatus(1)
              }
            }
          },
          error: function () {
            // 找不到团信息, 则直接开团
            console.log('找不到团信息, 则直接开团');
            setGroupBuyStatus(0)
          }
        })
      }
      // 在团成员当中了
      function inGroup () {
        return buyersIds.length > 0 && buyersIds.indexOf(user.id) !== -1;
      }
      // 设置团购状态
      function setGroupBuyStatus (_status) {
        status = _status
        stepCreate.removeClass('active')
        stepJoin.removeClass('active')
        stepShare.removeClass('active')
        stepDone.removeClass('active')
        groupBtn.off('click')
        switch (status) {
          case 0: // 立即开团
            groupBtn.text('立即开团')
            groupBtn.on('click', submitOrder)
            stepCreate.addClass('active')
            break
          case 1: // 立即参团
            groupBtn.text('立即参团')
            groupBtn.on('click', submitOrder)
            stepJoin.addClass('active')
            break
          case 2: // 立即分享
            groupBtn.text('邀请好友参团')
            groupBtn.on('click', showShare)
            stepShare.addClass('active')
            break
          case 3: // 重新开团
            groupBtn.text('重新开团')
            groupBtn.on('click', submitOrder)
            stepDone.addClass('active')
            break
        }
      }
      // 渲染团购进度
      function renderProcess () {
        if (buyersIds.length >=  2) $('#process').addClass("step-1")
        if (buyersIds.length >=  5) $('#process').addClass("step-2")
        if (buyersIds.length >= 10) $('#process').addClass("step-3")
        if (buyersIds.length >= 20) $('#process').addClass("step-4")
      }
      // 获取团购成员信息
      function getGroupBuyerList() {
        account.ajax({
          auth: false,
          type: 'GET',
          path: '/s/students/socials',
          data: {ids: buyersIds.slice((page-1)*pageSize, page*pageSize).toString()},
          success: function (result) {
            buyers = buyers.concat(result)
            renderGroupBuyerList()
          },
          error: function (err) {
            $.toastAlert(err.message, 2);
          }
        });
      }
      // 渲染团购成员信息
      function renderGroupBuyerList() {
        var groupBuyList = '', dividerList = ''
        var total = buyersIds.length;
        var showTotal = (page * pageSize) > total ? total : (page * pageSize);
        _.forEach(buyers, function (item, index) {
          if (total > showTotal && index == showTotal - 1) {
            groupBuyList += '<div id="more" class="group-member"><img src="' + CDN_RESOURCE + '/mobile/campaign/award/icon/ic_add.png"><span>更多</span></div>'
          } else {
            groupBuyList += '<div class="group-member"><img src="' + item.avatar + '" onerror="this.src=\'' + CDN_RESOURCE + '/mobile/campaign/award/icon/ic_add.png\'" ><span>' + item.nickname + '</span></div>'
            if (index < showTotal - 1) dividerList += '<div class="divider" style="top: ' + 95.5 * parseInt(index/5) + 'px;"><div></div><div></div><div></div></div>'
          }
        })
        $('#groupBuyList').empty().append(groupBuyList);
        $('#dividerList').empty().append(dividerList);
        $('#more').off('click').on('click', function () {
          page++;
          getGroupBuyerList();
        })
      }
      // 提交订单
      function submitOrder() {
        account.forceLogin = true;
        account.getUserInfo(function (err, user) {
          if (err) {
            $.toastAlert(user.message);
          } else {
            account.ajax({
              type: 'POST',
              path: '/s/bills',
              data: {
                productId: pid,
                payChannel: utils.isWechat() ? 'weixin' : 'alipay',
                returnUrl: window.location.protocol + '//' + window.location.host + '/wx/verifypayment/' + pid,
                tradeType: 'JSAPI',
                openId: window.localStorage.getItem(account.openId),
                bigGroupBuyingId: status === 1 ? gid : ''
              },
              success: function (data) {
                //唤起微信支付
                if (data.status !== 'error') {
                  if (utils.isWechat()) {
                    wxconfig.pay(data.bill_id, pid, JSON.parse(data.jsApiParameters), campUrl)
                  } else {
                    window.location.href = data.url
                  }
                } else {
                  $.toastAlert('下单失败，请重试')
                }
              },
              error: function (err) {
                if (err.code === 'product.rejected.by.bought.products') {
                  $.toastAlert('您已经参加活动')
                  getGroupBuyInfo()
                }
              }
            });
          }
        });
      }
      // 显示分享
      function showShare () {
        $('.share-mask').fadeIn();
      }
      // 设置时间倒计时
      function setGroupBuyCountDown(endAt) {
        starCount = setInterval(function () {
          var timestamp = Date.parse(new Date());
          if (timestamp >= endAt) {
            // 团购已经结束
            clearInterval(starCount);
            day1.text(0);
            day2.text(0);
            hour1.text(0);
            hour2.text(0);
            min1.text(0);
            min2.text(0);
          } else if (timestamp < endAt) {
            var timeDiff = endAt - timestamp;
            var day = Math.floor(timeDiff / 1000 / 60 / 60 / 24);
            var hour = Math.floor(timeDiff / 1000 / 60 / 60 % 24);
            var min = Math.floor(timeDiff / 1000 / 60 % 60);
            if (day < 10) day = "0" + day;
            if (hour < 10) hour = "0" + hour;
            if (min < 10) min = "0" + min;
            day += '';
            hour += '';
            min += '';
            day1.text(day.slice(0, 1));
            day2.text(day.slice(1, 2));
            hour1.text(hour.slice(0, 1));
            hour2.text(hour.slice(1, 2));
            min1.text(min.slice(0, 1));
            min2.text(min.slice(1, 2));
          }
        }, 1000);
      }
      // 初始化微信配置
      function initWxConfig () {
        var configOption = {
          timestamp: '{{$signature['timestamp']}}',
          nonceStr: '{{$signature['nonceStr']}}',
          signature: '{{$signature['signature']}}',
          jsApiList: ['onMenuShareTimeline', 'chooseWXPay', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareQZone']
        }
        wxconfig = new WxConfig(configOption, 'award')
      }
      // 设置微信分享
      function activeShare (shareFlag) {
        if (!/(MicroMessenger)/i.test(navigator.userAgent)) return;
        wxconfig.activeShare(shareFlag || '', '', {
          title: '【久趣特惠团购】给4-12岁儿童的北美外教超值英语课！',
          desc: '严选北美外教在线授课，创造趣味十足的课堂体验，让孩子爱学更有效。',
          link: window.location.protocol + '//wx2.97kid.com/wx/award/' + Math.ceil(Math.random() * 100) + '?_r=' + (shareFlag ? shareFlag : '') + (gid ? '&gid='  + gid : ''),
          imgUrl: 'https://static-app.97kid.com/site-student/public/img/share.png'
        })
      }
      // 获取团购id
      function getGid () {
        var gidFromUrl = utils.getQueryString('gid'), gidFromLS = window.localStorage.getItem('_gid')
        if (gidFromUrl) {
          window.localStorage.setItem('_gid', gidFromUrl)
          return gidFromUrl
        } else if (gidFromLS) {
          window.localStorage.removeItem('_gid')
          return gidFromLS
        } else {
          return null
        }
      }

      //切换账号
      $('.account').off('click').on('click',function() {
        account._showLogin(function () {});
      });
      $('#closeAccount').off('click').on('click',function(){
        $('.account-mask').fadeOut();
      })
      $('.switch-account').off('click').on('click', function () {
        $('.account-mask').fadeOut();
        account._showLogin(function () {});
      });
    }()
  </script>
@stop